from django.contrib.auth.backends import ModelBackend
from users.models import UserProfile
from django.db.models import Q

class BoxueguModelBackend(ModelBackend):
    # def authenticate(self, request, username=None, password=None, **kwargs):
    #     try:
    #         #  验证用户是否为邮箱登录，如果是则验证密码，如果不是则返回空值
    #         user = UserProfile.objects.get(username=username)
    #     except:
    #         try:
    #             #  验证用户是否为手机登录，如果是则验证密码，如果不是则返回空值
    #             user= UserProfile.objects.get(mobile=username)
    #         except:
    #             try:
    #                 # 验证是否为管理员登陆，如果是则验证密码，不是则返回空值
    #                 user =  UserProfile.objects.get(username=username,is_superuser=True,is_staff=True)
    #             except:
    #                 return None
    #     if user.check_password(password):
    #         return user
    #     else:
    #         return None
    def authenticate(self, request, username=None, password=None, **kwargs):

        if request is None:
            try:
                # 判断是否是超级管理员用户
                user =  UserProfile.objects.get(
                        Q(username=username,is_superuser=True,is_staff=True)|
                        Q(email=username,is_superuser=True,is_staff=True)
                        )
            except:
                return None
            # 判断密码
            if user.check_password(password):
                return user
            else:
                return None
        else:
            # 变量username的值，可以是用户名，也可以是手机号，需要判断，再查询
            try:
                user =  UserProfile.objects.get(
                    Q(username=username)|Q(mobile=username))
            except:
                # 如果未查到数据，则返回None，用于后续判断
                return None

            # 判断密码
            if user.check_password(password):
                return user
            else:
                return None










